import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../layouts/MainLayout.vue'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Register from '../views/Register.vue'
import BookModule from '../views/BookModule.vue'
import Profile from '../views/Profile.vue'
import { authApi } from '../api/auth'
import PostDetail from '../views/PostDetail.vue'
import GoodsPublish from '../views/GoodsPublish.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        redirect: '/home'
      },
      {
        path: '/home',
        name: 'Home',
        component: Home
      },
      {
        path: '/partner',
        name: 'Partner',
        component: () => import('../views/Partner.vue')
      },
      {
        path: '/resources',
        name: 'Resources',
        component: () => import('../views/Resources.vue')
      },
      {
        path: '/secondhand',
        name: 'SecondHand',
        component: () => import('../views/SecondHand.vue')
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue')
      },
      {
        path: '/book',
        name: 'BookModule',
        component: BookModule,
        meta: { requiresAuth: true }
      },
      {
        path: '/goodspublish',
        name: 'GoodsPublish',
        component: GoodsPublish
      },
      {
        path: '/post/:id',
        name: 'PostDetail',
        component: () => import('@/views/PostDetail.vue')  // 动态导入推荐
      }
    ]
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')

  // 如果用户已登录且尝试访问登录页面，重定向到主页
  if (to.path === '/login' && token) {
    next('/home')
    return
  }

  // 如果路由需要认证且用户未登录，重定向到登录页面
  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  }

  // 如果有token，进行验证
  if (token) {
    try {
      await authApi.getUserInfo(token) // 调用后端接口验证 token
    } catch (error) {
      // 如果验证失败，清除 token 并重定向到登录页面
      console.error('Token 验证失败:', error)
      localStorage.removeItem('token')
      next({ path: '/login', query: { redirect: to.fullPath } })
      return
    }
  }

  next()
})

export default router
